//
//  ChatDAO.m
//  GolfFriend
//
//  Created by Vescky on 14-2-24.
//  Copyright (c) 2014年 vescky.org. All rights reserved.
//

#import "ChatDAO.h"
#import "UserSession.h"

#define TB_CHAT @"tb_chat"

@implementation ChatDAO
static ChatDAO *defaultChatDAO;
//-- id
//-- fromId 发送人的id
//-- toId 接收人的id
//-- content 信息内容
//-- time 发送时间
//-- isRead 是否读取
//-- msgType txt/pic/vox/gfNews
//-- sourceLink 资源的位置

+ (id)shareChatDAO {
    if (!defaultChatDAO) {
        defaultChatDAO = [[ChatDAO alloc] init];
        DB *dbase = [[DB alloc] init];
        FMDatabase *database = [dbase getDatabase];
        [database executeUpdate:[NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@(recordId integer primary key,msgId integer,fromId text,toId text,content text,time text,msgType text,isRead text,sourceLink text)",TB_CHAT]];
        [database close];
    }
    return defaultChatDAO;
}

- (bool)saveMessage:(NSDictionary*)_dict {
    if (!_dict) {
        return NO;
    }
    
    if ([self isMessageExist:[_dict objectForKey:@"id"]]) {
        return NO;
    }
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithDictionary:_dict];
    if (isValueSet([_dict objectForKey:@"id"])) {
        [params setObject:[_dict objectForKey:@"id"] forKey:@"msgId"];
        [params removeObjectForKey:@"id"];
    }
    
    if ([params objectForKey:@"isGroupChat"]) {
        [params removeObjectForKey:@"isGroupChat"];
    }
    
    if (!params || [params count] < 1) {
        return NO;
    }
    
    if (![self isMessageExist:[params objectForKey:@"msgId"]]) {
        [self insert:params inTable:TB_CHAT];
    }
    
    return YES;
}

- (bool)saveMessages:(NSMutableArray*)_arr {
    if (!_arr || [_arr count] < 1) {
        return NO;
    }
    for (int i = 0; i < [_arr count]; i++) {
        [self saveMessage:[_arr objectAtIndex:i]];
    }
    return YES;
}

- (NSString*)getOneMessageByUserId:(NSString*)_uId {
    NSString *qConfition = [NSString stringWithFormat:@"select * from %@ where (fromId = '%@' and toId = '%@') or (fromId = '%@' and toId = '%@') order by msgId desc limit 1",TB_CHAT,_uId,[[UserSession shareUserSession] getUserId],[[UserSession shareUserSession] getUserId],_uId];
    NSMutableArray *arr = [self queryByConfition:qConfition];
    if (arr && [arr count] > 0) {
        return [arr objectAtIndex:0];
    }
    return nil;
}

- (NSDictionary*)getLatestMessageByUserId:(NSString*)_uId {
    NSString *qConfition = [NSString stringWithFormat:@"select * from %@ where (fromId = '%@' and toId = '%@') or (fromId = '%@' and toId = '%@') order by msgId desc limit 1",TB_CHAT,_uId,[[UserSession shareUserSession] getUserId],[[UserSession shareUserSession] getUserId],_uId];
    NSMutableArray *arr = [self queryByConfition:qConfition];
    if (arr && [arr count] > 0) {
        return [arr objectAtIndex:0];
    }
    return nil;
}

- (NSMutableArray*)getMessagesByUserId:(NSString*)_uId {
    NSString *qConfition = [NSString stringWithFormat:@"select * from %@ where (fromId = '%@' and toId = '%@') or (fromId = '%@' and toId = '%@') order by msgId desc",TB_CHAT,_uId,[[UserSession shareUserSession] getUserId],[[UserSession shareUserSession] getUserId],_uId];
    return [self queryByConfition:qConfition];
}

- (NSMutableArray*)getUnreadMessageByUserId:(NSString*)_uId {
    NSString *qConfition = [NSString stringWithFormat:@"select * from %@ where (fromId = '%@' and toId = '%@' and  isRead = '0') or (fromId = '%@' and toId = '%@' and  isRead = '0') order by msgId desc",TB_CHAT,_uId,[[UserSession shareUserSession] getUserId],[[UserSession shareUserSession] getUserId],_uId];
    return [self queryByConfition:qConfition];
}

- (NSMutableArray*)getMessagesByUserId:(NSString*)_uId range:(NSRange)_range {
    int beginIndex = _range.location;
    int endIndex = _range.location + _range.length;
    if (beginIndex < 0) {
        beginIndex = 0;
    }
    if (endIndex < beginIndex) {
        endIndex = beginIndex + 1;
    }
    NSString *qConfition = [NSString stringWithFormat:@"select * from %@ where (fromId = '%@' and toId = '%@') or (fromId = '%@' and toId = '%@') order by msgId desc limit %d,%d",TB_CHAT,_uId,[[UserSession shareUserSession] getUserId],[[UserSession shareUserSession] getUserId],_uId,beginIndex,endIndex];
    return [self queryByConfition:qConfition];
}

- (bool)readMessage:(NSString*)msgId {
    if (!msgId || msgId.length < 1) {
        return NO;
    }
    DB *dbase = [[DB alloc] init];
    FMDatabase *database = [dbase getDatabase];
    return [database executeUpdate:[NSString stringWithFormat:@"update %@ set isRead = '1' where msgId = '%@' ",TB_CHAT,msgId]];
}

- (bool)readUserMessage:(NSString*)_uId {
    if (!_uId || _uId.length < 1) {
        return NO;
    }
    DB *dbase = [[DB alloc] init];
    FMDatabase *database = [dbase getDatabase];
    return [database executeUpdate:[NSString stringWithFormat:@"update %@ set isRead = '1' where fromId = '%@' ",TB_CHAT,_uId]];
}

- (NSMutableArray*)getAllUnreadMessages {
    NSString *qConfition = [NSString stringWithFormat:@"select * from %@ where isRead = '0' order by msgId desc",TB_CHAT];
    return [self queryByConfition:qConfition];
}

- (bool)deleteUserMessages:(NSString*)userId {
    DB *dbase = [[DB alloc] init];
    FMDatabase *database = [dbase getDatabase];
    return [database executeUpdate:[NSString stringWithFormat:@"delete * from %@ where fromId = '%@' or toId = '%@'",TB_CHAT,userId,[[UserSession shareUserSession] getUserId]]];
}

- (bool)cleanAllMessages {
    DB *dbase = [[DB alloc] init];
    FMDatabase *database = [dbase getDatabase];
    bool flag = [database executeUpdate:[NSString stringWithFormat:@"delete from %@",TB_CHAT]];
    if (flag) {
        flag = [database executeUpdate:[NSString stringWithFormat:@"update sqlite_sequence set seq=0 where name = '%@'",TB_CHAT]];
    }
    [database close];
    return flag;
}

- (long)getLatestMsgId {
    NSString *sql = [NSString stringWithFormat:@"select msgId from %@ order by msgId desc limit 1",TB_CHAT];
    NSMutableArray *rArr = [self queryByConfition:sql];
    if (isValueSet(rArr)) {
        NSDictionary *rDct = [rArr objectAtIndex:0];
        return [[rDct objectForKey:@"msgId"] longLongValue];
    }
    return 0;
}


#pragma mark - Private
- (bool)isMessageExist:(NSString*)msgId {
    if (!msgId || msgId.length < 1) {
        return NO;
    }
    NSString *qConfition = [NSString stringWithFormat:@"select * from %@ where msgId = '%@' limit 1",TB_CHAT,msgId];
    NSMutableArray *arr = [self queryByConfition:qConfition];
    if (arr && [arr count] > 0) {
        return YES;
    }
    return NO;
}

@end
